<template>
  <div class="settings-container">
    <h2 class="settings-title">个人设置</h2>

    <!-- 个人信息卡片 -->
    <div class="profile-card">
      <div class="profile-header">
        <div class="user-basic-info">
          <h3 class="username">{{ userInfo.username }}</h3>
          <p class="user-type">{{ userTypeText }}</p>
        </div>
      </div>

      <div class="profile-details">
        <div class="info-item">
          <span class="info-label">用户名：</span>
          <span class="info-value">{{ userInfo.username }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">用户类型：</span>
          <span class="info-value">{{ userTypeText }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">注册时间：</span>
          <span class="info-value">{{ formatDate(userInfo.date_joined) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">最后登录：</span>
          <span class="info-value">{{ formatDate(userInfo.last_login) }}</span>
        </div>
      </div>

      <div class="profile-actions">
        <button class="edit-btn" @click="showEditForm = true">
          修改个人信息
        </button>
      </div>
    </div>

    <!-- 编辑表单弹窗 -->
    <div v-if="showEditForm" class="modal-overlay" @click="closeEditForm">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>修改个人信息</h3>
          <button class="close-btn" @click="closeEditForm">&times;</button>
        </div>
        <form class="edit-form" @submit.prevent="handleSubmit">
          <div class="form-group">
            <label for="username">用户名</label>
            <input
              type="text"
              id="username"
              v-model="editForm.username"
              placeholder="请输入用户名"
              required
            />
          </div>
          <div class="form-group">
            <label for="password">新密码</label>
            <input
              type="password"
              id="password"
              v-model="editForm.password"
              placeholder="留空表示不修改"
            />
          </div>
          <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input
              type="password"
              id="confirmPassword"
              v-model="editForm.confirmPassword"
              placeholder="再次输入新密码"
            />
          </div>
          <div class="form-error" v-if="errorMsg">{{ errorMsg }}</div>
          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="closeEditForm">
              取消
            </button>
            <button type="submit" class="submit-btn" :disabled="isSubmitting">
              {{ isSubmitting ? "提交中..." : "保存修改" }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { getUserInfo, updateSelfUser } from "../../api/user.js";
import { useStore } from "vuex";
import axiosInstance from "../../utils/requests.js";

// 创建store实例
const store = useStore();
// 用户信息数据
const userInfo = reactive({
  id: "",
  username: "",
  user_type: "",
  date_joined: "",
  last_login: "",
});

// 编辑表单状态
const showEditForm = ref(false);
const isSubmitting = ref(false);
const errorMsg = ref("");

// 编辑表单数据
const editForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
});

// 计算属性
const userTypeText = computed(() => {
  return userInfo.user_type === "admin" ? "管理员" : "普通用户";
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "暂无信息";
  try {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch (error) {
    return dateString;
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo();
    if (response.code === 0 && response.data) {
      Object.assign(userInfo, response.data);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 打开编辑表单
const openEditForm = () => {
  // 初始化表单数据
  editForm.username = userInfo.username;
  editForm.password = "";
  editForm.confirmPassword = "";
  errorMsg.value = "";
  showEditForm.value = true;
};

// 关闭编辑表单
const closeEditForm = () => {
  showEditForm.value = false;
};

// 处理表单提交
const handleSubmit = async () => {
  // 表单验证
  if (!editForm.username.trim()) {
    errorMsg.value = "用户名不能为空";
    return;
  }

  if (editForm.password && editForm.password !== editForm.confirmPassword) {
    errorMsg.value = "两次输入的密码不一致";
    return;
  }

  isSubmitting.value = true;
  errorMsg.value = "";

  try {
    const userData = {
      id: userInfo.id,
      username: editForm.username,
      password: editForm.password || undefined,
    };

    const response = await updateSelfUser(userData);

    if (response.code === 0) {
      // 更新本地数据
      userInfo.username = editForm.username;
      showEditForm.value = false;

      // 同步更新Vuex store中的用户信息
      store.commit("user/SET_USER", { username: editForm.username });

      // 同时更新localStorage中的用户名
      localStorage.setItem("username", editForm.username);

      // 显示成功提示
      alert("个人信息更新成功！");
    } else {
      errorMsg.value = response.msg || "更新失败";
    }
  } catch (error) {
    errorMsg.value = error.message || "更新失败，请重试";
    console.error("更新用户信息失败:", error);
  } finally {
    isSubmitting.value = false;
  }
};

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<style lang="less" scoped>
.settings-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.settings-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
}

.profile-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.profile-header {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.user-basic-info {
  flex: 1;
  text-align: center;
}

.username {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #333;
}

.user-type {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.profile-details {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
}

.info-label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.profile-actions {
  text-align: center;
}

.edit-btn {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.edit-btn:hover {
  background: #66b1ff;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.edit-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #333;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.admin-only {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.form-error {
  color: #f56c6c;
  font-size: 12px;
  margin-bottom: 15px;
  padding: 10px;
  background: #fef0f0;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background: #909399;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.cancel-btn:hover {
  background: #a6a9ad;
}

.submit-btn {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background: #66b1ff;
}

.submit-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-container {
    padding: 10px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
  }

  .info-item {
    flex-direction: column;
  }

  .info-label {
    width: auto;
    margin-bottom: 5px;
  }
}
</style>
